package cn.xerllent.wxtp.handler;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ExecutorService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import cn.xerllent.wxtp.entity.WxCorp;
import cn.xerllent.wxtp.service.WxCorpService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.common.session.WxSessionManager;
import me.chanjar.weixin.cp.bean.WxCpTpAuthInfo;
import me.chanjar.weixin.cp.bean.message.WxCpTpXmlMessage;
import me.chanjar.weixin.cp.bean.message.WxCpXmlOutMessage;
import me.chanjar.weixin.cp.tp.service.WxCpTpService;

/**
 * @author sxh
 * 企业取消授权处理
 */
@Component
@Slf4j
public class AuthCancelHandler extends AbstractHandler {

	private final WxCorpService wxCorpService;
	
	@Autowired
	@Qualifier("singleThreadExecutor")
	private ExecutorService singleThreadExecutor;

	public AuthCancelHandler(WxCorpService wxCorpService) {
		super();
		this.wxCorpService = wxCorpService;
	}
	
	  @Override
	  public WxCpXmlOutMessage handle(WxCpTpXmlMessage wxMessage,
	              Map<String, Object> context,
	              WxCpTpService wxCpTpService,
	              WxSessionManager sessionManager) {
			try {
				String suiteId = wxMessage.getSuiteId();
				String authCorpId = wxMessage.getAuthCorpId();
				WxCorp wxCorp = wxCorpService.getOne(new LambdaQueryWrapper<WxCorp>().eq(WxCorp::getCorpId, authCorpId).eq(WxCorp::getSuiteId,suiteId));
				if(wxCorp!=null) {
					wxCorp.setUpdatetime(LocalDateTime.now()).setStatus(-1);
					wxCorpService.updateById(wxCorp);
				}
				// TODO: 后续应用初数据操作

				log.info("取消授处理：" + wxCorp.getAgentId());
			} catch (Exception e) {
				log.error("取消授处理 err:" , e);
			}
		  return null;
	  }
}
